<template>
  <div>
    <div ref="echarts1" style="width: 500px;height: 500px;"></div>
    <button @click="chg"> 点我 </button>
  </div>
</template>

<script>
import * as echarts from 'echarts'
// 引入socket.io
import io from 'socket.io-client'
export default {
  data () {
    return {
      mychart1: undefined,
      wbsocket: undefined
    }
  },
  mounted () {
    this.showEcharts1()
    // 初始化socket
    this.initSocket()
  },
  methods: {
    showEcharts1 () {
      this.mychart1 = echarts.init(this.$refs.echarts1)
      const option = {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            id: '12',
            name: '销量',
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'bar'
          },
          {
            id: '22',
            name: '收获量',
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'line'
          }
        ]
      }
      this.mychart1.setOption(option)
    },
    // 初始化socket
    initSocket () {
      // 1.创建socket对象
      this.wbsocket = io('ws://127.0.0.1:5000/work')
      // 2.监听服务端发送的消息
      this.wbsocket.on('my_response', (data) => {
        // 3.接收服务端发送的消息
        data = JSON.parse(data)
        // 重新设置数据
        this.mychart1.setOption({
          series: [
            {
              id: '12',
              name: '销量',
              data: data.ll,
              type: 'bar'
            },
            {
              id: '22',
              name: '收获量',
              data: data.l2,
              type: 'bar'
            }
          ]
        })
      })

      this.wbsocket.on('my_cc', (data) => {
        // 3.接收服务端发送的消息
        console.log(JSON.parse(data))
        this.chg(JSON.parse(data))
      })
    },
    chg (data) {
      // 重新设置数据
      this.mychart1.setOption({
        series: [
          {
            id: '22',
            name: '收获量',
            data: data,
            type: 'bar'
          }
        ]
      })
    }
  },

}
</script>

<style lang="scss" scoped></style>
